<?php

namespace doujunyu\utility\tencent;

use doujunyu\utility\tencen\im\package\TLSSigAPIv2;

/**
 * 腾讯即时通讯
 * https://cloud.tencent.com/document/product/269/1520
 */
class Im
{
    //腾讯即时通讯
    protected $im_url = "https://console.tim.qq.com/";
    protected $sdkappid = '';
    protected $key = '';
    protected $identifier = 'administrator';
    protected $prefix = '';
    public function __construct($sdkappid,$key)
    {
        $this->sdkappid = $sdkappid;
        $this->key = $key;
    }
    public function set_identifier($identifier){
        $this->identifier = $identifier;
    }


    /**Notes:导入单个账号
     */
    public function account_import($uid, $avatar, $nickname){
        $uid = $this->prefix.$uid;
        $data = [
            'UserID'=>"$uid",
            'Nick'=>$nickname,
            'FaceUrl'=>$avatar
        ];
        $url = $this->im_url.'v4/im_open_login_svc/account_import?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',[]];
    }

    /**Notes:生成用户签名
     */
    public function gen_user_sig(){
        $tlssig_api = new TLSSigAPIv2($this->sdkappid,$this->key);
        return $tlssig_api->genUserSig($this->identifier,300);
    }

    /**Notes:设置用户信息
     */
    public function portrait_set($uid, $nickname, $avatar){
        $uid = $this->prefix.$uid;
        $ProfileItem = [];
        if($nickname){
            $ProfileItem[] =   [
                'Tag'=>'Tag_Profile_IM_Nick',
                'Value'=>$nickname,
            ];
        }
        if($avatar){
            $ProfileItem[] =   [
                'Tag'=>'Tag_Profile_IM_Image',
                'Value'=>$avatar,
            ];
        }
        $data = [
            'From_Account'=>"$uid",
            'ProfileItem'=>$ProfileItem,
        ];
        $url = $this->im_url.'v4/im_open_login_svc/account_import?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);
        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',[]];
    }

    public function delAccount($deleteDatas){
        $DeleteItem = [];
        if($deleteDatas){
            foreach ($deleteDatas as $v){
                $DeleteItem[] = [
                    'UserID' => $this->prefix.$v
                ];
            }
        }
        $data = [
            'DeleteItem'=>$DeleteItem
        //        [
        //        ['UserID'=>"11"],
        //        ['UserID'=>"12"],
        //        ['UserID'=>"13"],
        //        ['UserID'=>"14"],
        //        ['UserID'=>"15"],
        //        ['UserID'=>"16"],
        //        ['UserID'=>"17"],
        //        "11","12","13","14","15","16","17"
        //    ],
        ];
        $url = $this->im_url.'v4/im_open_login_svc/account_delete?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',[]];
    }

    /**
     * 批量发单聊消息
     */
    public function batchsendmsg($send_user_id, $receive_user_ids, $message_datas){
        $To_Account = [];
        foreach ($receive_user_ids as $v){
            $To_Account[] = $this->prefix.$v;
        }
        $MsgBody = [];
        foreach ($message_datas as $v){
            $MsgBody[] = [
                'MsgType' => 'TIMCustomElem',
                'MsgContent' => [
        //                    'Desc' => '您有一条新的消息'
                    'Ext' => json_encode([
                        'dataType' => $v['type'],
                        'fileSize' => $v['filesize'],
                        'fileName' => $v['filename'],
                    ]),
                    'Data' => $v['message'],
                ]
            ];
        }
        $data = [
            'SyncOtherMachine' => 1,//1：把消息同步到 From_Account 在线终端和漫游上 ,2不同步
            'From_Account' => $this->prefix.$send_user_id,
            'To_Account' => $To_Account,
            'MsgRandom' => rand(10000, 99999),
            'MsgBody' => $MsgBody
        ];
        $url = $this->im_url.'v4/openim/batchsendmsg?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',[]];
    }

    /** 单发单聊
     *  https://cloud.tencent.com/document/product/269/2282
     *  {
     *  "SyncOtherMachine": 1, // 消息同步至发送方
     *  "From_Account": "lumotuwe1", //消息发送方 UserID
     *  "To_Account": "lumotuwe2", //消息接收方 UserID
     *  "OnlineOnlyFlag": 1,
     *  "MsgSeq": 93847636,
     *  "MsgRandom": 1287657,
     *  "MsgBody": [
     *      {
     *          "MsgType": "TIMTextElem",
     *          "MsgContent": { //消息
     *              "Text": "hi, beauty"
     *          }
     *      }
     *  ],
     *  "CloudCustomData": "your cloud custom data"
     *  }
     */
    public function sendmsg($from_Account,$to_Account,$msg_body){
        $data['SyncOtherMachine'] = 1;// 消息同步至发送方
        $data['From_Account'] = $this->prefix.$from_Account;
        $data['To_Account'] = $this->prefix.$to_Account;
        $data['MsgRandom'] = rand(10000, 99999);
        $data['MsgBody'] = [
            [
                "MsgType" => 'TIMTextElem',
                'MsgContent' => [
                    'Text' => $msg_body,
                ]
            ]
        ];
       
        $url = $this->im_url.'v4/openim/sendmsg?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',[]];
    }

    /** 拉取单聊历史消息
     *  https://cloud.tencent.com/document/product/269/42794
     *  {
     *    "Operator_Account":"user2", //会话其中一方的 UserID，以该 UserID 的角度去查询消息。
     *    "Peer_Account":"user1", //会话的另一方 UserID
     *    "MaxCnt":100, //请求的消息条数
     *    "MinTime":1584669600, //请求的消息时间范围的最小值
     *    "MaxTime":1584673200 //请求的消息时间范围的最大值
     *    "LastMsgKey": aaaaaa //【选填】上一次拉取到的最后一条消息的 MsgKey，续拉时需要填该字段，填写方法见上方
     *  }
     */
    public function admin_getroammsg($Operator_Account , $Peer_Account, $MaxCnt = 100, $MinTime, $MaxTime,$LastMsgKey){
        $data = [
            "Operator_Account"=>$Operator_Account,
            "Peer_Account"=>$Peer_Account,
            "MaxCnt"=>$MaxCnt,
            "MinTime"=>$MinTime,
            "MaxTime"=>$MaxTime
        ];
        $url = $this->im_url.'v4/openim/admin_getroammsg?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',[]];
    }

    /** 拉取会话列表
     *  https://cloud.tencent.com/document/product/269/62118
     *  {
     *    "From_Account": "id1", //填 UserID，请求拉取该用户的会话列表。
     *    "TimeStamp": 0, //普通会话的起始时间，第一页填 0。
     *    "StartIndex": 0, //普通会话的起始位置，第一页填 0。
     *    "TopTimeStamp": 0, //置顶会话的起始时间，第一页填 0。
     *    "TopStartIndex": 0, //置顶会话的起始位置，第一页填 0。
     *    "AssistFlags": 15 //会话辅助标志位：填固定值 15。
     *  }
     */
    public function getList($From_Account,$TimeStamp = 0,$StartIndex = 0,$TopTimeStamp = 0,$TopStartIndex = 0,$AssistFlags = 15){
        $data = [
            "From_Account"=> $From_Account,
            "TimeStamp"=> $TimeStamp,
            "StartIndex"=> $StartIndex,
            "TopTimeStamp"=> $TopTimeStamp,
            "TopStartIndex"=> $TopStartIndex,
            "AssistFlags"=> $AssistFlags
        ];
        
        $url = $this->im_url.'v4/recentcontact/get_list?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',[]];
    }

    /** 创建群组
     * 
     */
    public function create_group($owner_account,$type,$name){

        $data = [
            'Owner_Account'=>"$owner_account",// 群主的 UserId（选填）
            'Type'=>$type,// 群组类型：Private/Public/ChatRoom/AVChatRoom/Community
            'Name'=>$name,// 群名称（必填）
        ];
        $url = $this->im_url.'v4/group_open_http_svc/create_group?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',$res_arr];
    }

    /** 删除群组
     */
    public function destroy_group($group_id){
        $data = [
            'GroupId'=>$group_id,// 群组 ID
        ];
        $url = $this->im_url.'v4/group_open_http_svc/destroy_group?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',$res_arr];
    }

    /** 发送群组信息
     */
    public function send_group_msg($group_id,$message){
        $data = [
            'GroupId'=>$group_id,// 群组 ID
            'MsgBody'=>[
                [
                    'MsgType'=>'TIMTextElem',// 消息类型
                    'MsgContent'=>[
                        'Text'=>$message,// 消息内容
                    ]
                ]
            ]
        ];
        $url = $this->im_url.'v4/group_open_http_svc/send_group_msg?'.$this->get_commen_param($this->identifier);
        $res = $this->postCurl($url,$data);
        $res_arr = json_decode($res,true);

        if(!isset($res_arr['ActionStatus'])){
            return ['im返回结构错误',[]];
        }
        if( $res_arr['ActionStatus'] != 'OK'){
            return [$res_arr['ErrorCode'].'|'.$res_arr['ErrorInfo'],[]];
        }
        return ['',$res_arr];
    }


























    private function get_commen_param($identifier = null){
        $identifier = $identifier ?: $this->identifier;
        $tlssig_api = new TLSSigAPIv2($this->sdkappid,$this->key);
        $data = [
            'sdkappid' => $this->sdkappid,
            'identifier' => $identifier,
            'usersig' => $tlssig_api->genUserSig($identifier, 300),
            'random' => rand(0, 4294967295),  // 缺少 random 参数
            'contenttype' => 'json'  // 缺少 contenttype 参数
        ];
        return http_build_query($data);
    }

    /** CURL Post发送数据
     * @param $url string 地址
     * @param $option array 参数数据
     * @param int $header  消息头
     * @param string $type 发送方式
     * @return mixed
     */
    private function postCurl($url, $option = [], $header = 0, $type = 'POST') {
        $curl = curl_init (); // 启动一个CURL会话
        curl_setopt ( $curl, CURLOPT_URL, $url ); // 要访问的地址
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE ); // 对认证证书来源的检查
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE ); // 从证书中检查SSL加密算法是否存在
        curl_setopt ( $curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器
       curl_setopt($curl, CURLOPT_HTTPHEADER, array(
               'Content-Type: application/json; charset=utf-8',
               'Content-Length: ' . strlen( json_encode($option) ))
       );
        if (! empty ( $option )) {
            $options = json_encode ( $option );
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $options ); // Post提交的数据包
        }
        curl_setopt ( $curl, CURLOPT_TIMEOUT, 30 ); // 设置超时限制防止死循环
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 获取的信息以文件流的形式返回
        curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, $type );
        $result = curl_exec ( $curl ); // 执行操作

        curl_close ( $curl ); // 关闭CURL会话
        return $result;
    }
}